//
//  UITextView+emoticon.swift
//  微博分支表情键盘
//
//  Created by JJ on 15/9/13.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit

extension UITextView{
    
    
    var emoticonText:String{
    
        let attrText=attributedText
        var strM=String()
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dic, range, _) -> Void in
            
            if let attachment=dic["NSAttachment"] as? EmoticonAttachment{
                strM += attachment.chs
                
            }else{
                let str=(attrText.string as NSString).substringWithRange(range)
                
                strM += str
            }
        }
        print(strM)
       return strM

    }
    
    func insertEmoticon(emoticon:Emoticon){
        
        if emoticon.isEmpty{
            return
        }
        if emoticon.isRemove{
            deleteBackward()
            return
        }
        
        if emoticon.emoji != nil{
            
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        
        let imageStr=EmoticonAttachment.emoticonAttranbutetText(emoticon, font: font!)
        
        let strM=NSMutableAttributedString(attributedString: attributedText)
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageStr)
        
        let range=selectedRange
        attributedText=strM
        selectedRange=NSRange(location: range.location + 1, length: 0)
        
        delegate?.textViewDidChange!(self)
    }
    
    
}
